<style lang="less">
    @import '../../../styles/common.less';
    @import '../../my-components/data-table/table.less';
</style>

<template>
  <div>
      <Row>
        <Col span="24">
            <Card>
                <p slot="title">
                    <!-- <Icon type="android-more-horizontal"></Icon> -->
                    城市管理
                </p>
                <Row>
                    <Col span="16">
                        <Input  v-model="searchData.cityName" @on-keyup.enter="getData" placeholder="请输入城市..." style="width: 150px" />
                        <Button type="primary" shape="circle" icon="ios-search" @click="getData"></Button>
                    </Col>
                    <Col span="3" offset="5" v-if="$hasPerms('city:save')">
                        <span style="margin: 0 10px;">                   
                            <Button type="primary" icon="plus" @click="handleAdd()">新增城市</Button>                          
                        </span>
                    </Col>
                </Row>
                <br>
                <Row>
                    <div>
                        <data-table :is-loading="isLoading" v-model="citys" :columns-list="cityColumns"
                                    :total-record="total" :current-page="currentPage" :permissions-prefix="permsSign"
                            @deleteOne="handleDel" @editOne="handleEdit" @changePage="changePage">
                        </data-table>
                    </div>
                </Row>
            </Card>
        </Col>
      </Row>
      <Modal
            v-model="addModal"
            :title="modalTitle"
            :closable='false'
            :mask-closable="false">
        <Form ref="addFrom" :model="addFrom" label-position="top" :rules="rules">
            <FormItem label="城市名" prop="cityName">
                <Input v-model="addFrom.cityName" />
            </FormItem>
            <FormItem label="排序号">
                <InputNumber v-model="addFrom.sorts"></InputNumber>
            </FormItem>
            <FormItem label="热门">
                <template>
                    <Switch v-model="addFrom.hot" :true-value="1" :false-value="2" >
                        <span slot="open">是</span>
                        <span slot="close">否</span>
                    </Switch>
                </template>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="text" @click="cancelModal">取消</Button>
            <Button type="primary" :loading="saveLoading" @click="addModalOk">保存</Button>
        </div>
      </Modal>
  </div>

</template>

<script>
import dataTable from '../../my-components/data-table/dataTable.vue';

export default {
    name: 'city-index',
    components: {
        dataTable
    },
    data () {
        let validateCityName = (rule, value, callback) => {
            if (!this.isAddCity && this.initCityName === value) {
                callback();
            } else {
                this.checkCityName(value, callback);
            }
        };
        return {
            isLoading: true,
            saveLoading: false,
            isAddCity: false,
            permsSign: 'city',
            searchData: {},
            // 表头
            cityColumns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: 'ID',
                    key: 'id',
                    align: 'center'
                },
                {
                    title: '城市',
                    align: 'center',
                    key: 'cityName'
                },
                {
                    title: '热门',
                    align: 'center',
                    key: 'hot',
                    render: (h, params) => {
                        return h('i-switch', {
                            props: {
                                value: params.row.hot === 1
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                'on-change': () => {
                                    this.changeHot(params.row);
                                }
                            }
                        });
                    }
                },
                {
                    title: '排序号',
                    align: 'center',
                    key: 'sorts',
                    sortable: true
                },
                {
                    title: '创建时间',
                    align: 'center',
                    key: 'createTime'
                },
                {
                    title: '操作',
                    align: 'center',
                    key: 'handle',
                    handle: ['edit', 'delete']
                }
            ],
            initCityName: '',
            // 数据
            citys: [],
            total: 0,
            currentPage: 1,
            modalTitle: '',
            addModal: false,
            addFrom: {
                id: 0,
                cityName: '',
                sorts: null,
                hot: 2
            },
            rules: {
                cityName: [
                    {required: true, message: '名称不能为空', trigger: 'blur'},
                    { validator: validateCityName, trigger: 'blur' }
                ]
            }
        };
    },
    methods: {
        getData () {
            this.$get('/city/list?pageNum=' + this.currentPage, this.searchData)
                .then(res => {
                    // console.log(res);
                    this.citys = res.records;
                    this.total = res.total;
                    this.currentPage = res.current;
                    this.isLoading = false;
                })
                .catch(error => {
                    this.isLoading = false;
                });
        },
        cancelModal () {
            this.addModal = false;
        },
        handleAdd () {
            this.isAddCity = true;
            this.addModal = true;
            this.modalTitle = '添加城市';
            this.addFrom = {
                id: 0,
                cityName: '',
                sorts: null,
                hot: 2
            };
        },
        handleEdit (val) {
            this.isAddCity = false;
            this.addModal = true;
            this.$get('/city/info/' + val.id)
                .then(res => {
                    this.modalTitle = '编辑城市';
                    this.initCityName = res.cityName;
                    this.addFrom.id = res.id;
                    this.addFrom.cityName = res.cityName;
                    this.addFrom.sorts = res.sorts;
                    this.addFrom.hot = res.hot;
                    // console.log(res);
                }).catch(error => {
                    this.$Message.error('获取城市信息失败');
                });
        },
        addModalOk () {
            this.$refs.addFrom.validate((valid) => {
                if (valid) {
                    let url = '/city/update';
                    if (this.isAddCity) {
                        url = '/city/save';
                    }
                    this.saveLoading = true;
                    this.$post(url, {
                        id: this.addFrom.id === 0 ? null : this.addFrom.id,
                        cityName: this.addFrom.cityName,
                        sorts: this.addFrom.sorts,
                        hot: this.addFrom.hot
                    }, 'json')
                        .then(res => {
                            this.getData();
                            this.$Message.success('操作成功');
                            this.addModal = false;
                            this.saveLoading = false;
                        })
                        .catch(error => {
                            this.saveLoading = false;
                            this.$Message.error(error.message);
                        });
                } else {
                    this.saveLoading = false;
                    // 获取表单域所有field
                    let fields = this.$refs.addFrom.fields;
                    // 聚焦错误表单域
                    try {
                        fields.forEach(element => {
                            if (element.validateState === 'error') {
                                // 这里的element无foucs()
                                let refName = element.prop;
                                this.$refs[refName].focus();
                                // 抛出异常跳出循环
                                foreach.break = new Error('StopIteration');
                            }
                        });
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
        handleDel (val, index) {
            // 删除
            let cityIds = [];
            cityIds.push(val.id);
            this.$del('/city/delete',
                cityIds, 'json'
            ).then(res => {
                this.$Message.success('删除了' + val.cityName);
                this.getData();
            }).catch(error => {
                console.log(error);
                this.$Message.error(error.message);
            });
        },
        handleSelectAll (status) {
            // this.$manager.selection.selectAll(status);
        },
        changePage (val) {
            this.currentPage = val;
            this.getData();
        },
        changeHot (row) {
            let url = 'city/unhot/';
            if (row.hot === 2) {
                url = 'city/hot/';
            }
            this.saveLoading = true;
            this.$post(url + row.id)
                .then(res => {
                    this.$Message.success('操作成功');
                    this.addModal = false;
                    this.saveLoading = false;
                })
                .catch(error => {
                    this.saveLoading = false;
                    this.$Message.error(error.message);
                });
        },
        checkCityName (value, callback) {
            this.$get('/city/checkName?name=' + value)
                .then(res => {
                    if (res >= 1) {
                        callback(new Error('城市名称已被使用'));
                    } else {
                        callback();
                    }
                })
                .catch(e => {
                    this.sloading = false;
                });
        }
    },
    created () {
        this.getData();
    }
};
</script>
